package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV2;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Map;

import static com.atguigu.realtime.common.Constant.*;

/**
 * @Author lzc
 * @Date 2022/7/25 14:12
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV2 {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow().init(
            3002,
            2,
            "Dws_02_DwsTrafficVcChArIsNewPageViewWindow",
            TOPIC_DWD_TRAFFIC_PAGE,
            TOPIC_DWD_TRAFFIC_UV_DETAIL,
            TOPIC_DWD_TRAFFIC_UJ_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          Map<String, DataStreamSource<String>> topicAndStreamMap) {
        
        // 1. 每个流解析成同一种类型, 再union成一个流
        DataStream<TrafficPageViewBean> beanStream = parseAndUnionOne(topicAndStreamMap);
        
        // 2. 分组 开窗 聚合
        SingleOutputStreamOperator<TrafficPageViewBean> aggregatedStream = windowAndAgg(beanStream);
        
        // 3. 把结果写入到clickhouse中
        writeToClickHouse(aggregatedStream);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficPageViewBean> aggregatedStream) {
        aggregatedStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window", TrafficPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(DataStream<TrafficPageViewBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(15))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(bean -> bean.getVc() + "_" + bean.getCh() + "_" + bean.getAr() + "_" + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .sideOutputLateData(new OutputTag<TrafficPageViewBean>("late") {})
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean value1,
                                                      TrafficPageViewBean value2) throws Exception {
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setUjCt(value1.getUjCt() + value2.getUjCt());
                        return value1;
                    }
                },
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TrafficPageViewBean> elements,
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                        
                        bean.setTs(ctx.currentProcessingTime());  // 把ts更新为聚合时间
                        //                        bean.setTs(System.currentTimeMillis());  // 把ts更新为聚合时间
                        
                        out.collect(bean);
                    }
                }
            );
    }
    // reduce aggregate process
    
    private DataStream<TrafficPageViewBean> parseAndUnionOne(Map<String, DataStreamSource<String>> topicAndStreamMap) {
        
        // 1. pv sv durSum
        SingleOutputStreamOperator<TrafficPageViewBean> pvSvDurSumStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_PAGE)
            .map(new MapFunction<String, TrafficPageViewBean>() {
                @Override
                public TrafficPageViewBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");
                    
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    Long uvCt = 0L;
                    Long svCt = page.getString("last_page_id") == null ? 1L : 0L;  // ( 会话数) last_page_id is null, 开启了一个新的会话, 对sv的贡献是1
                    Long pvCt = 1L;  // 每个页面日志, 对pv的共享都应该是 1
                    Long durSum = page.getLong("during_time") == null ? 0L : page.getLong("during_time");
                    Long ujCt = 0L;
                    
                    return new TrafficPageViewBean(
                        "", "",
                        vc, ch, ar, isNew,
                        uvCt, svCt, pvCt, durSum, ujCt,
                        ts
                    );
                }
            });
        
        // 2. uv
        SingleOutputStreamOperator<TrafficPageViewBean> uvStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_UV_DETAIL)
            .map(new MapFunction<String, TrafficPageViewBean>() {
                @Override
                public TrafficPageViewBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");
                    
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    Long uvCt = 1L;
                    Long svCt = 0L;  // ( 会话数) last_page_id is null, 开启了一个新的会话, 对sv的贡献是1
                    Long pvCt = 0L;  // 每个页面日志, 对pv的共享都应该是 1
                    Long durSum = 0L;
                    Long ujCt = 0L;
                    
                    return new TrafficPageViewBean(
                        "", "",
                        vc, ch, ar, isNew,
                        uvCt, svCt, pvCt, durSum, ujCt,
                        ts
                    );
                }
            });
        
        // 3.uj
        SingleOutputStreamOperator<TrafficPageViewBean> ujStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_UJ_DETAIL)
            .map(new MapFunction<String, TrafficPageViewBean>() {
                @Override
                public TrafficPageViewBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");
                    
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    Long uvCt = 0L;
                    Long svCt = 0L;  // ( 会话数) last_page_id is null, 开启了一个新的会话, 对sv的贡献是1
                    Long pvCt = 0L;  // 每个页面日志, 对pv的共享都应该是 1
                    Long durSum = 0L;
                    Long ujCt = 1L;
                    
                    return new TrafficPageViewBean(
                        "", "",
                        vc, ch, ar, isNew,
                        uvCt, svCt, pvCt, durSum, ujCt,
                        ts
                    );
                }
            });
        
        return pvSvDurSumStream.union(uvStream, ujStream);
    }
}
